package com.night.icm.common.jwt;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;

/**
 * JwtTokenUtil
 * JWT 工具类
 *
 * @author Liao ZhiYong
 * @date 2019/12/3
 */
@Component
public
class JwtTokenUtil {

    public static final String TOKEN_HEADER = "Authorization";
    public static final String TOKEN_PREFIX = "Bearer ";
    /**
     * 密钥
     */
    private static final String SECRET = "jwtsecretdemo";
    private static final String ISS = "zhiyong";

    /**
     * 角色的key
     */
    private static final String ROLE_CLAIMS = "rol";

    /**
     * 过期时间是3600秒，既是1个小时
     */
    private static final long EXPIRATION = 3600L;

    /**
     * 选择了记住我之后的过期时间为7天
     */
    private static final long EXPIRATION_REMEMBER = 604800L;

    /**
     * 创建token
     *
     * @param username     用户名
     * @param role         角色权限
     * @param isRememberMe 是否记住我，记住为7天
     * @return token
     */
    public static String createToken(String username, String role, boolean isRememberMe) {
        long expiration = isRememberMe ? EXPIRATION_REMEMBER : EXPIRATION;
        HashMap<String, Object> map = new HashMap<>();
        map.put(ROLE_CLAIMS, role);
        return Jwts.builder()
                .signWith(SignatureAlgorithm.HS512, SECRET)
                .setClaims(map)
                .setIssuer(ISS)
                .setSubject(username)
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + expiration * 1000))
                .compact();
    }

    /**
     * 从token中获取用户名
     *
     * @param token token
     * @return 返回值
     */
    public static String getUsername(String token) {
        return getTokenBody(token).getSubject();
    }

    /**
     * 获取用户角色
     *
     * @param token token
     * @return 返回值
     */
    public static String getUserRole(String token) {
        return (String) getTokenBody(token).get(ROLE_CLAIMS);
    }

    /**
     * 从token中读取Issue Date (发布时间)
     *
     * @param token token字符串
     * @return issue date
     */
    public static Date getIssueDateFromToken(String token) {
        Date issueAt = null;
        try {
            Claims claims = getTokenBody(token);
            if (claims != null) {
                issueAt = claims.getIssuedAt();
            }
        } catch (Exception e) {
            // nothing to do
        }
        return issueAt;
    }

    /**
     * 读取token失效时间
     *
     * @param token token
     * @return 时间
     */
    public static Date getExpirationDateFormToken(String token) {
        Date exp = null;
        try {
            Claims claims = getTokenBody(token);
            if (claims != null) {
                exp = claims.getExpiration();
            }
        } catch (Exception e) {
            // nothing to do
        }
        return exp;
    }

    /**
     * 检查token是否已过期
     *
     * @param token token
     * @return 是否过期
     */
    public static boolean isExpiration(String token) {
        try {
            return getTokenBody(token).getExpiration().before(new Date());
        } catch (ExpiredJwtException e) {
            return true;
        }
    }

    /**
     * 解析token，以获取token中的信息
     *
     * @param token token
     * @return 信息
     */
    private static Claims getTokenBody(String token) {
        return Jwts.parser()
                .setSigningKey(SECRET)
                .parseClaimsJws(token)
                .getBody();
    }
}